<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box{
            width: 100px;
            height: 100px;
            background-color:burlywood;
            position: absolute;
        }
    </style>
</head>
<body>
    <button>右</button>
    <button>左</button>
    <button>上</button>
    <button>下</button>
    <div class="box"></div>
    <script>
        let oBtns=document.querySelectorAll("button");
        let oBox=document.querySelector(".box");
        // 获取样式
        let gs=(o,attr)=>{
            if(o.currentStyle){
                return o.currentStyle[attr];
            }else{
                return window.getComputedStyle(o,null)[attr];
            }
        }
        // 封装方法
        const n=(o,attr,target)=>{
            // 1.清除定时器
            clearInterval(o.timer);
            // 2.开启一个新的定时器
            o.timer=setInterval(()=>{
                // 3.获取当前位置
                let current=parseInt(gs(o,attr));
                // 4.计算步长
                let step=target>current?10:-10;
                // 5.求出新的位置
                o.style[attr]=current+step+"px";
                // 6.判断剩余的路
                if(Math.abs(target-current)<=Math.abs(step)){
                    clearInterval(o.timer);
                    o.style[attr]=target+"px";
                }
            },50)
        }
        // 按钮事件
        oBtns[0].addEventListener("click",()=>{
            n(oBox,"left",500);
        })
        oBtns[1].addEventListener("click",()=>{
            n(oBox,"left",8);
        })
        oBtns[2].addEventListener("click",()=>{
            n(oBox,"top",30);
        })
        oBtns[3].addEventListener("click",()=>{
            n(oBox,"top",500);
        })
    </script>
</body>
</html>